#include "DataCollect.h"

CDataCollect::CDataCollect()
{
}

CDataCollect::~CDataCollect()
{

}

//函数名：Init
//函数功能:初始化DataCollect
//函数参数：无
//返回值:正确返回true，错误返回false
bool CDataCollect::Init()
{
    int result;

    InfoContainer = CInfoContainer::GetInstance();
    if(!InfoContainer)
        return false;

    SerialPort = CSerialPort::GetInstance();
    if(!SerialPort)
        return false;

    DataBase = CDataBase::GetInstance();
    if(!DataBase)
        return false;

    DevCreater = new CDevCreater();
    if(!DevCreater)
        return false;

    result = GetCmd();
    if(!result)
        return false;

    return true;
}

//函数名：Cleanup
//函数功能:反初始化函数，对该类使用的资源进行释放
//函数参数：无
//返回值:无
void CDataCollect::Cleanup()
{
    SerialPort->Cleanup();

    DataBase->Cleanup();

    Tool->Cleanup();

    InfoContainer->Cleanup();

    if(DevCreater)
    {
        delete DevCreater;
        DevCreater = 0;
    }
}

//函数名：GetCmd
//函数功能:获取所有需要采集的传感器设备的命令
//函数参数：无
//返回值:正确返回true，错误返回false
bool CDataCollect::GetCmd()
{
    ifstream In;
    string Data;
    vector <string> ZigbeeID;

    In.open(ZigBeeID);
    if(!In.is_open())
        return false;
    while(getline(In, Data))
    {
        string CurData(Data.begin(), Data.begin()+2);
        if(CurData == "##")
            continue;
        else if(Data.length() != 0)
        {
            string TempID(Data.begin(), Data.begin()+4);
            if(TempID == "8000")
                break;
            ZigbeeID.push_back(TempID);
        }
    }

    for(vector <string>::iterator Cur_ZigbeeID = ZigbeeID.begin(); Cur_ZigbeeID != ZigbeeID.end(); Cur_ZigbeeID++)
    {
        int Devtype;
        string Cmd;
        CSensorDev * SensorDev;
        InfoContainer->GetSensorTypeInfo(*Cur_ZigbeeID, Devtype);
        SensorDev = DevCreater->CreateSensorDev(Devtype);
        if(!SensorDev)
            continue;

        SensorDev->GetCmd(Cmd);
        Cmd = *Cur_ZigbeeID + Cmd;
        SensorCmd.push_back(Cmd);
        //cout << "cmd" << Cmd << endl;

        if(SensorDev)
        {
            delete SensorDev;
            SensorDev = NULL;
        }
    }
    return true;
}

//函数名：DataPicker
//函数功能:数据采集函数
//函数参数：(in)int & CollectFlag:数据采集模块标记位, （in）int & TerminalFlag：终端发送命令模块标记位, （in）pthread_mutex_t & ComLock：进程锁
//返回值:无
void CDataCollect::DataPicker(int & CollectFlag, int & TerminalFlag, pthread_mutex_t & ComLock)
{
    for(vector <string>::iterator Cur_SensorCmd = SensorCmd.begin(); Cur_SensorCmd != SensorCmd.end(); Cur_SensorCmd++)
    {
        string Data;
        pthread_mutex_lock(&ComLock);
        if(TerminalFlag == TERMINALFREE)
        {
            CollectFlag = COLLECTBUSY;
            //pthread_mutex_unlock(&ComLock);

            if(SerialPort->Run(*Cur_SensorCmd, Data) == false)
            {
                char time[15];
                string CurID((*Cur_SensorCmd).begin(), (*Cur_SensorCmd).begin() + 4);
                Tool->GetRecentTime(time);
                cout << time << " " <<"ZigbeeID:" <<  CurID << " collect data fail, please check." << endl;
                ReturnData.push_back(CurID);
            }
            else
                ReturnData.push_back(Data);

            CollectFlag = COLLECTFREE;
            pthread_mutex_unlock(&ComLock);
            usleep(100);
        }
//        else
//        {
//            pthread_mutex_unlock(&ComLock);
//            while(TerminalFlag == TERMINALBUSY)
//                usleep(1000);
//            Cur_SensorCmd--;
//        }
    }
}

//函数名：DataAnalyse
//函数功能:数据分析函数，将采集到的数据进行分析
//函数参数：无
//返回值:无
void CDataCollect::DataAnalyse()
{
    for(vector <string>::iterator Cur_Data = ReturnData.begin(); Cur_Data != ReturnData.end(); Cur_Data++ )
    {
        CSensorDev * SensorDev = NULL;
        int DevType;
        USensorData TempData;
        struct CachedData Data;
        string CurID((*Cur_Data).begin(), (*Cur_Data).begin() + 4);

        if(InfoContainer->GetSensorTypeInfo(CurID, DevType) == false)
        {
            cout << "Cannot find CurID: " << CurID << ", please check again" << endl;
            continue;
        }
        SensorDev = DevCreater->CreateSensorDev(DevType);
        SensorDev->GetData(*Cur_Data, TempData);

        strcpy(Data.Id, CurID.c_str());
        Data.Type = DevType;
        Data.Values.FirstValue = TempData.Values.FirstValue;
        Data.Values.SecondValue = TempData.Values.SecondValue;

        SensorData.push_back(Data);

        if(SensorDev)
        {
            delete SensorDev;
            SensorDev = NULL;
        }
    }
    ReturnData.clear();

}

//函数名：SaveData
//函数功能:将经过分析的数据保存到数据库里面
//函数参数：无
//返回值:无
void CDataCollect::SaveData()
{
    DataBase->InsertCachedData(SensorData);
    SensorData.clear();
}

//函数名：Run
//函数功能:数据采集运行函数
//函数参数：(in)int & CollectFlag:数据采集模块标记位, （in）int & TerminalFlag：终端发送命令模块标记位, （in）pthread_mutex_t & ComLock：进程锁
//返回值:无
void CDataCollect::Run(int &CollectFlag, int &TerminalFlag, pthread_mutex_t &ComLock)
{
    DataPicker(CollectFlag, TerminalFlag, ComLock);
    DataAnalyse();
    SaveData();
}




